package com.lagou.servlet;

import com.lagou.bena.Student;
import com.lagou.service.AdminServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "updateServlet", urlPatterns = "/update")
public class updateServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码格式
        request.setCharacterEncoding("utf-8");
        // 获取前段页面输入的学号
        Integer id = Integer.parseInt(request.getParameter("stuID"));
        AdminServiceImp asi = new AdminServiceImp();
        // 根据学号查找到student对象
        Student student = asi.findByIdService(id);

        // 对前段用户输入的数据进行判断。
        // 如果对应输入框中的值不为空，就执行修改，否则保持不变(选择性修改)
        if (!"".equals(request.getParameter("stuName"))) {
            student.setStuName(request.getParameter("stuName"));
        }
        if (!"".equals(request.getParameter("sex"))) {
            student.setSex(request.getParameter("sex"));
        }
        if (!"".equals(request.getParameter("birthday"))) {
            student.setBirthday(request.getParameter("birthday"));
        }
        if (!"".equals(request.getParameter("email"))) {
            student.setEmail(request.getParameter("email"));
        }
        if (!"".equals(request.getParameter("info"))) {
            student.setInfo(request.getParameter("info"));
        }

        // 对影响的行数进行判断，大于0则修改成功，小于0则修改失败
        int res = asi.updateStuService(student);
        if (res > 0) {
            // 修改学生信息成功，跳转到学生列表
            // 查询所有学生信息，得到list集合
            List<Student> students = asi.showAllService();
            // 将查询出的所有学生信息集合存入session对象中实现多个请求共享
            request.getSession().setAttribute("students", students);
            request.getSession().setAttribute("updateRes", "success");
            // 实现客户端的跳转
            response.sendRedirect("stuList.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
